package com.csw.android.player.service

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.os.Build
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.Observer
import com.csw.android.player.PlayerManager
import com.csw.android.player.base.MediaInfo
import com.csw.android.player.ui.full.FullScreenPlayActivity
import com.csw.android.player.view.window.OnFloatWindowChangeListener
import com.csw.android.player.view.window.VideoFloatWindow

/**
 * 播放服务，使用前台服务实现，减少被回收的概率，提供播放控制通知，处理通知的播放控制事件
 */
class PlayService : LifecycleService() {

    companion object {
        /**
         * 启动播放服务
         */
        fun startService(context: Context) {
            ContextCompat.startForegroundService(context, Intent(context, PlayService::class.java))
        }

        /**
         * 关闭播放服务
         */
        fun stopService(context: Context) {
            context.stopService(Intent(context, PlayService::class.java))
        }

        const val REQUEST_CODE: Int = 100
        const val ACTION_NOTIFICATION_CLICK: String = "notification_click"
        const val ACTION_PLAY_NEXT: String = "play_next"
        const val ACTION_PLAY_PREVIOUS: String = "play_previous"
        const val ACTION_PLAY_CURR: String = "play_curr"
        const val ACTION_PAUSE_CURR: String = "pause_curr"
        const val ACTION_FULL_SCREEN: String = "full_screen"
        const val ACTION_FLOAT_WINDOW: String = "float_window"
    }

    private val playMediaListener = Observer<MediaInfo?> {
        playControlNotification.videoImageUrl = it?.coverUri.toString()
        playControlNotification.title = it?.mediaUri.toString()
        playControlNotification.previousButtonVisibility =
            if (PlayerManager.SINGLE_PLAYER.playList?.hasPrevious() == true) View.VISIBLE
            else View.GONE
        playControlNotification.nextButtonVisibility =
            if (PlayerManager.SINGLE_PLAYER.playList?.hasNext() == true) View.VISIBLE
            else View.GONE
    }

    private val playerInfoListener = Observer<Long?> {
        playControlNotification.isPlaying =
            PlayerManager.SINGLE_PLAYER.playerInfo?.buttonPlaying == true
    }

    private val playControlReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null) {
                when (intent.action) {
                    ACTION_NOTIFICATION_CLICK -> {
//                MainActivity.openActivity(this)
                    }

                    ACTION_PLAY_NEXT -> PlayerManager.SINGLE_PLAYER.playList?.playNext()
                    ACTION_PLAY_PREVIOUS -> PlayerManager.SINGLE_PLAYER.playList?.playPrevious()
                    ACTION_PLAY_CURR -> PlayerManager.SINGLE_PLAYER.playList?.playCurrent()
                    ACTION_PAUSE_CURR -> PlayerManager.SINGLE_PLAYER.pause()
                    ACTION_FULL_SCREEN -> FullScreenPlayActivity.open(
                        this@PlayService, PlayerManager.SINGLE_PLAYER.playId, null
                    )

                    ACTION_FLOAT_WINDOW -> VideoFloatWindow.instance.run {
                        show()
                        startPlay(PlayerManager.SINGLE_PLAYER.playId)
                    }
                }
            }
        }
    }
    private lateinit var playControlNotification: PlayControlNotification
    override fun onCreate() {
        super.onCreate()
        playControlNotification = PlayControlNotification(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(
                PlayControlNotification.NOTIFICATION_ID,
                playControlNotification.createNotification(),
                ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
            )
        } else {
            startForeground(
                PlayControlNotification.NOTIFICATION_ID,
                playControlNotification.createNotification(),
            )
        }

        PlayerManager.SINGLE_PLAYER.run {
            playList?.currMedia?.observe(this@PlayService, playMediaListener)
            playerInfo?.onInfoUpdate?.observe(this@PlayService, playerInfoListener)
        }
        VideoFloatWindow.instance.onFloatWindowChangeListener =
            object : OnFloatWindowChangeListener {
                override fun onFloatWindowVisibilityChanged(isVisibility: Boolean) {
                    playControlNotification.floatWindowButtonVisibility =
                        if (isVisibility) View.GONE
                        else View.VISIBLE
                }
            }

        val intentFilter = IntentFilter()
        intentFilter.addAction(ACTION_NOTIFICATION_CLICK)
        intentFilter.addAction(ACTION_PLAY_NEXT)
        intentFilter.addAction(ACTION_PLAY_PREVIOUS)
        intentFilter.addAction(ACTION_PLAY_CURR)
        intentFilter.addAction(ACTION_PAUSE_CURR)
        intentFilter.addAction(ACTION_FULL_SCREEN)
        intentFilter.addAction(ACTION_FLOAT_WINDOW)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(playControlReceiver, intentFilter, RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(playControlReceiver, intentFilter)
        }
    }

    override fun onDestroy() {
        unregisterReceiver(playControlReceiver)
        VideoFloatWindow.instance.onFloatWindowChangeListener = null
        super.onDestroy()
    }

}